<template>
	<view class="page__content">
		<u-navbar :title="pageConfig.titleName" leftIconColor="#fff" rightIconColor="#fff" :autoBack="true"
			:fixed="false">
		</u-navbar>

		<view class="page__content__main">
			<!-- 判断当前蓝牙适配器是否开启 -->
			<template v-if="pageConfig.showTemplate && 
				(pageConfig.deviceTypeName == 'Bluetooth' || pageConfig.deviceTypeName == 'HID')">
				<!-- 应用内 - 蓝牙连接 -->
				<template v-if="pageConfig.deviceTypeName == 'Bluetooth'">
					<page-link-bluetooth></page-link-bluetooth>
				</template>

				<!-- 应用外 - 系统蓝牙连接 -->
				<template v-else-if="pageConfig.deviceTypeName == 'HID'">
					<page-link-hid></page-link-hid>
				</template>
			</template>


			<!-- 未开启蓝牙适配器，且是蓝牙模块 -->
			<template v-else-if="!pageConfig.showTemplate && 
				(pageConfig.deviceTypeName == 'Bluetooth' || pageConfig.deviceTypeName == 'HID')">
				<!-- 提示开启蓝牙适配器 -->

				<u-empty text="开启蓝牙,以便查找附近蓝牙设备" iconSize="150" icon="/static/tabbar-icons/Bluetooth.png"
					style="height:'35vh'">
					<u-button @click="openBluetoothAdapter" size="small" type="primary" :style="{marginTop:10+'px'} "
						text="立即开启"></u-button>
				</u-empty>
			</template>


			<!-- 应用内 - 串口连接 -->
			<template v-if="pageConfig.deviceTypeName == 'Serial'">
				<!-- <linkSerial></linkSerial> -->
			</template>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();

	// const plugin = uni.requireNativePlugin('harmony-bluetooth')
	import pageLinkBluetooth from "@/st_qms/components/page_index/device_link_bluetooth"
	import pageLinkHid from "@/st_qms/components/page_index/device_link_hid"

	let pageConfig = reactive<any>({
		showTemplate: false, // 判断蓝牙适配器是否开启
		titleName: "", // 导航栏名称
		deviceTypeName: "", // 当前选中设备的类型
	})
	// qmsStore.DeviceLinkConfig

	let choiceDeviceInfo = reactive({});

	// 获取选中的临时设备数据
	const baseParam = uni.$utils.deepClone(qmsStore.DeviceLinkConfig.tempData_device
		.deviceInfo) || {};

	Object.assign(choiceDeviceInfo, baseParam);

	pageConfig.titleName = baseParam?.MeasureName || "设备连接";
	pageConfig.deviceTypeName = baseParam.Communication;

	// const initData = uni.$utils.$bluetooth.openBluetooth()



	// 获取当前蓝牙适配器状态
	const adapterState = computed(() => {
		return bluetoothStore.adapterState.available;
	});
	console.log(adapterState.value);

	// 获取一遍历史记录的蓝牙状态
	pageConfig.showTemplate = adapterState.value;
	// 监听蓝牙适配器状态
	watch(adapterState, (nval : any, oval : any) => {
		console.log(nval);
		pageConfig.showTemplate = nval;
		if (nval && !oval) {

		}

	}, { deep: true });


	const sysDeviceInfo = mainStore.systemConfig.sysDeviceInfo;

	function openBluetoothAdapter() {
		switch (sysDeviceInfo.platform) {
			case "android":
				const BluetoothAdapter = plus.android.importClass(
					'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
				const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
				console.log(blueadapter);
				if (blueadapter) {
					setTimeout(() => {
						// 判断蓝牙是否开启
						if (blueadapter.isEnabled()) {
							console.log('开启')

						} else {
							// 尝试开启蓝牙（Android原生方法）
							const isOpened = blueadapter.enable(); // 返回boolean，true表示开启成功（部分设备可能需要用户确认）
							console.log('开启结果：', isOpened);
						}
					}, 50)
				}
				break;
			case "ios":
				break;
			default:
				break;
		}
	}


	const getBluetoothState = (maxRetries = 5) => {
		return new Promise((resolve, reject) => {
			let retryCount = 0;

			const execute = () => {

				// #ifdef APP-HARMONY
				// plugin.getBluetoothState()

				// resolve(true);
				// #endif



				// #ifndef APP-HARMONY
				uni.getBluetoothAdapterState({
					success(res) {
						console.log('蓝牙状态:', res);
						resolve(res); // 成功时解析 Promise
					},
					async fail(err) {
						console.log('蓝牙状态:', err);
						retryCount++;

						if (err.code == 10000 && retryCount <= maxRetries) {
							console.log(`第 ${retryCount} 次重试，剩余 ${maxRetries - retryCount} 次`);
							try {
								await uni.$utils.$bluetooth.openBluetooth();
								execute(); // 继续下一次尝试
							} catch (openError) {
								reject(openError); // 打开蓝牙失败时拒绝 Promise
							}
						} else if (retryCount > maxRetries) {
							console.log(`已达到最大重试次数 ${maxRetries} 次，停止重试`);
							reject(new Error(`获取蓝牙状态失败，已重试 ${maxRetries} 次`));
						} else {
							console.log('其他错误，停止重试:', err);
							reject(err); // 其他错误码，拒绝 Promise
						}
					}
				});
				// #endif
			};

			// 开始执行
			execute();
		});
	};


	onLoad(() => {
		getBluetoothState(3).then(state => {
			console.log('最终获取到的蓝牙状态:', state);
			bluetoothStore.adapterState = state;
		}).catch(error => {
			console.error('获取蓝牙状态失败:', error);
		});
	})

	onUnload(() => {
		qmsStore.DeviceLinkConfig.tempData_device.deviceInfo = {};

	})
</script>


<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		&__main {}
	}
</style>